package com.pocket.insight.base.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.pocket.insight.entity.AppParam;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 描述：
 *
 * @author shuize
 * @create 2024/12/13
 */
public class AppParamContext {

    private static TransmittableThreadLocal<Map<Long, AppParam.ValueMap>> appParamValueMapThreadLocal = new TransmittableThreadLocal();

    public static Map<Long, AppParam.ValueMap> getThreadLocalValue() {
        return (Map)appParamValueMapThreadLocal.get();
    }

    public static void setThreadLocalValue(Map<Long, AppParam.ValueMap> value) {
        appParamValueMapThreadLocal.set(value);
    }

    public static AppParam.ValueMap getAppParamValueMap(Long appId) {
        if (appParamValueMapThreadLocal.get() == null) {
            appParamValueMapThreadLocal.set(new HashMap());
        }

        if (!((Map)appParamValueMapThreadLocal.get()).containsKey(appId)) {
            ((Map)appParamValueMapThreadLocal.get()).put(appId, new AppParam.ValueMap(appId));
        }

        return (AppParam.ValueMap)((Map)appParamValueMapThreadLocal.get()).get(appId);
    }

    public static Map<String, Object> getAppParamValues(Long appId) {
        return getAppParamValueMap(appId).getAppParamNameValueMap();
    }

    public static void setSpecificAppParamValue(Long appId, String paramName, Object paramValue) {
        if (paramName != null) {
            getAppParamValues(appId).put(paramName, paramValue);
        }

    }

    public static Object getSpecificAppParamValueByName(Long appId, String paramName) {
        return getAppParamValues(appId).get(paramName);
    }

    public static boolean containsSpecificAppParamValueByName(Long appId, String paramName) {
        return appId != null && StringUtils.isNotBlank(paramName) ? getAppParamValues(appId).containsKey(paramName) : false;
    }

    public static Boolean isAppParamFetched(Long appId) {
        return appParamValueMapThreadLocal.get() != null && ((Map)appParamValueMapThreadLocal.get()).containsKey(appId);
    }

    public static void remove() {
        appParamValueMapThreadLocal.remove();
    }

}
